import appUtil from '@/utils/appUtil';
export default function URLConverter (url, data, convertRules, useDefaultRules) {
    if (!this instanceof URLConverter) {
        throw new Error('please user keyword "new" to construct a URLConverter!');
    }

    if (!appUtil.isString(url)) {
        throw new Error('the first parameter must be a url typed string!');
    }

    if (convertRules && !(appUtil.isArray(convertRules) || appUtil.isBoolean(convertRules))) {
        throw new TypeError('the third parameter must be an array or a boolean');
    } else if (appUtil.isBoolean(convertRules)) {
        useDefaultRules = convertRules;
        this.convertRules = useDefaultRules ? DEFAULT_CONVERTER_RULES : [];
    } else {
        this.convertRules = useDefaultRules ? DEFAULT_CONVERTER_RULES.concat(convertRules) : convertRules;
    }

    this.url = url;
    this.data = data;
    this.converted = false;
}

URLConverter.prototype.convert = function (convertRules) {
    if(convertRules && !appUtil.isArray(convertRules)) {
        throw new TypeError('convertRules should be an array!');
    } else if (convertRules) {
        this.convertRules = this.convertRules.concat(convertRules);
    }

    if (this.convertRules) {
        this.convertURL = this.convertRules.reduceRight((val, ruleFn) => {
            return ruleFn(val);
        }, this.url);
    }
    this.converted = true;

    return this.convertURL;
};

URLConverter.prototype.revert = function (revertRules) {
    // 如果没有传入恢复规则，则默认恢复到原始url
    if (!revertRules) {
        return this.url;
    } else if (!appUtil.isArray(revertRules)) {
        return revertRules.reduceRight((val, ruleFn) => {
            return ruleFn(val);
        }, this.url);
    }
};

URLConverter.prototype.equal = function (url) {
    return this.url === url || this.convertURL === url;
};

const DEFAULT_CONVERTER_RULES = [];
export function addSvUserId (url) {
    return url;
}
addSvUserId.revert = function (url) {
    return url;
};

export function convertXfunction (url, data) {
    //只给8.5并且非内部的菜单添加这些参数
    if (data && !data.isBuiltin && url.indexOf('redirectUrl=') < 0) {
        url = url + '?menuid=' + data.id + '&appFunction=' + data.id + '&id=' + data.id;
    }
}